package cn.huiyunche.driver.service.impl;


import cn.huiyunche.base.service.interfaces.UserService;
import cn.huiyunche.base.service.mappers.DWaybillMapper;
import cn.huiyunche.base.service.model.CMdvBillDetail;
import cn.huiyunche.base.service.model.CMdvBillSummary;
import cn.huiyunche.base.service.model.DWaybill;
import cn.huiyunche.base.service.model.DWaybillExample;
import cn.huiyunche.base.service.vo.CBillSummaryVo;
import cn.huiyunche.driver.service.CMdvBillDetailService;
import cn.huiyunche.driver.service.CMdvBillSummaryService;
import cn.huiyunche.driver.service.TmsQueryBillService;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;


/**
 * Created by Ligl on 2017/3/7.
 */
@Service
public class TmsQueryBillServiceImpl implements TmsQueryBillService {


    private static final Logger LOGGER = LoggerFactory.getLogger(TmsQueryBillServiceImpl.class);


    @Autowired
    private CMdvBillSummaryService cMdvBillSummaryService;

    @Autowired
    private CMdvBillDetailService cMdvBillDetailService;

    @Autowired
    private DWaybillMapper dWaybillMapper = null;

    @Autowired
    private UserService userService;


    /**
     * 查询tms账单
     *
     * @param resultStr
     * @return
     */
    public void tmsQueryBill(String resultStr) {
        if (StringUtils.isNotBlank(resultStr)) {
            JSONObject jsonObject = JSONObject.parseObject(resultStr);
            String data = jsonObject.getString("data");
            if (StringUtils.isNoneBlank(data)) {
                LOGGER.info("TmsQueryBillService.tmsQueryBill  data : {}.", data);
                List<CBillSummaryVo> resultList = null;
                try {
                    resultList = JSONArray.parseArray(data, CBillSummaryVo.class);
                } catch (Exception e) {
                    throw new BusinessException("===tms转换实体vo错误===");
                }
                if (resultList.size() == 0 || resultList == null) {
                    LOGGER.info("===没有获取到任何账单===", "");
                    return;
                }
                for (CBillSummaryVo cBillSummaryVo : resultList) {
                    //TMS账单费用明细
                    CMdvBillDetail detail = this.getCMdvBillDetail(cBillSummaryVo);
                    long detailId = cMdvBillDetailService.add(detail);
                    LOGGER.info("cMdvBillDetailService().add  detail : {}.", detail);
//                        CMdvBillDetailExample detailExample =  new CMdvBillDetailExample();
//                        detailExample.setOrderByClause("id DESC limit 1");
//                        Long detailId = this.getCMdvBillDetailMapper().selectByExample(detailExample).get(0).getId();
                    CMdvBillSummary summary = this.getCMdvBillSummary(cBillSummaryVo, detailId);
                    LOGGER.info("cMdvBillSummaryService().add  summary : {}.", summary);
                }
            }
        }
    }

    /**
     * 组装 CMdvBillDetail
     *
     * @param cBillSummaryVo
     * @return
     */
    private CMdvBillDetail getCMdvBillDetail(CBillSummaryVo cBillSummaryVo) {
        CMdvBillDetail detail = new CMdvBillDetail();
        detail.setDckmPay(cBillSummaryVo.getDckmpay());
        detail.setDcFestivalbonus(cBillSummaryVo.getDcfestivalbonus());
        detail.setDcFixed1(cBillSummaryVo.getDcfixed1());
        detail.setDcFixed2(cBillSummaryVo.getDcfixed2());
        detail.setDcSomebonus(cBillSummaryVo.getDcsomebonus());
        detail.setDctotalFuel(new BigDecimal(cBillSummaryVo.getDctotal_fuel()));
        detail.setDcModify(cBillSummaryVo.getDcmodify());
        detail.setDcSum(new BigDecimal(cBillSummaryVo.getDcsum()));
        detail.setDcFuel(cBillSummaryVo.getDcfuel());
        detail.setDcFuelUp(cBillSummaryVo.getDcfuelup());
        detail.setDcFuelFee(cBillSummaryVo.getDcfuelfee());
        detail.setDcPayRemainFuel(new BigDecimal(cBillSummaryVo.getDcpayremain_fuel()));
        detail.setDcInsFee(cBillSummaryVo.getDcinsfee());
        detail.setDcGpsFee(cBillSummaryVo.getDcgpsfee());
        detail.setDcZhicheBonus(new BigDecimal(cBillSummaryVo.getDczhiche_bonus()));
        detail.setDcAssesModify(new BigDecimal(cBillSummaryVo.getDcasses_modify()));
        detail.setDcPayReduce(new BigDecimal(cBillSummaryVo.getDcpayreduce()));
        detail.setDcPay(new BigDecimal(cBillSummaryVo.getDcpay()));
        detail.setDcPayByOilcard(new BigDecimal(cBillSummaryVo.getDcpay_by_oilcard()));
        detail.setVcMemo(cBillSummaryVo.getVcmemo());
        detail.setVcPeriod(cBillSummaryVo.getVcperiod());
        return detail;
    }

    /**
     * 组装 CMdvBillSummary
     *
     * @param cBillSummaryVo
     * @param detailId
     * @return
     */
    private CMdvBillSummary getCMdvBillSummary(CBillSummaryVo cBillSummaryVo, Long detailId) {
        CMdvBillSummary summary = new CMdvBillSummary();
        //判断是否存在用户
        Long userId = -1L;
        Long wayBillId = -1L;
        if (StringUtils.isBlank(cBillSummaryVo.getVcorderno())) {
            userId = -1L;
        }

        DWaybill dWaybill = this.getByTmsOrderCode(cBillSummaryVo.getVcorderno());
        if (null != dWaybill) {
            wayBillId = dWaybill.getId();
            userId = dWaybill.getUserId();
            LOGGER.info("TTmsQueryBillServiceImpl getByTmsOrderCode is not exist in dwaybill");
        }
        summary.setBillDetailId(String.valueOf(detailId));
        summary.setUserId(userId);
        summary.setDestCity(cBillSummaryVo.getVcdestcity());
        summary.setDtPrintDate(cBillSummaryVo.getDtprintdate());
        summary.setDtUpdateDate(cBillSummaryVo.getDtupdatedate());
        summary.setVcstyleNo(cBillSummaryVo.getVcstyleno());
        summary.setWaybillId(wayBillId);
        cMdvBillSummaryService.add(summary);
        return summary;
    }

    /**
     * 获取运单对象
     *
     * @param orderCode 订单编号
     * @return 运单对象
     */
    private DWaybill getByTmsOrderCode(String orderCode) {
        DWaybillExample dwe = new DWaybillExample();
        DWaybillExample.Criteria c = dwe.createCriteria();
        c.andOrderCodeEqualTo(orderCode).andUserIdGreaterThan(0L);
        List<DWaybill> list = this.dWaybillMapper.selectByExample(dwe);
        return list.size() > 0 ? list.get(0) : null;
    }

}
